var http = require("http");
var fs = require("fs");
var url = require("url");
var port = process.argv[2];

if (!port) {
  console.log("请指定端口好不好\n node server.js 8888 这样不会吗？");
  process.exit(1);
}

var server = http.createServer(function (request, response) {
  var parseUrl = url.parse(request.url, true);
  var pathWithQuery = request.url;
  var queryString = "";
  if (pathWithQuery.indexOf("?") >= 0) {
    queryString = pathWithQuery.substring(pathWithQuery.indexOf("?"));
  }
  var path = parseUrl.pathname;
  var query = parseUrl.query;
  var method = request.method;

  console.log("接收请求，路径为：" + pathWithQuery);

  if (path === "/") {
    response.statusCode = 200;
    response.setHeader("Content-Type", "text/html;charset=utf-8");
    response.write(`
      <!DOCTYPE html>
      <head>
        <link rel="stylesheet" href="/style">
      </head>
      <body>
        <h1>一生中最爱--feng</h1>
        <script src="/qian"></script>
      </body>
    `);
    response.end();
  } else if (path === "/style") {
    response.statusCode = 200;
    response.setHeader("Content-Type", "text/css;charset=utf-8");
    response.write(`body{text-align: center;}h1{color: red;}\n`);
    response.end();
  } else if (path === "/qian") {
    response.statusCode = 200;
    response.setHeader("Content-Type", "text/javascript;charset=utf-8");
    response.write(`console.log('这是JS内容')`);
    response.end();
  } else {
    response.statusCode = 404;
    response.setHeader("Content-Type", "text/html;charset=utf-8");
    response.write(`      
    <!DOCTYPE html>
    <head>
      <link rel="stylesheet" href="/style">
    </head>
    <body>
      <h1>404</h1>
      <h2>你访问的页面不存在</h2>
    </body>`);
    response.end();
  }
});

server.listen(port);
console.log(
  "监听 " +
    port +
    " 成功\n请在单杠上做后摆上转体360单手倒立然后另一只手打开 http://localhost:" +
    port
);
